package com.zzh.zzhaiagent.service.impl;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.zzh.zzhaiagent.exception.BusinessException;
import com.zzh.zzhaiagent.service.EmailService;
import com.zzh.zzhaiagent.utils.EmailRightUtils;
import com.zzh.zzhaiagent.utils.ResultCodeEnum;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

import static com.zzh.zzhaiagent.constant.RedisKeyConstant.EMAIL_CODE_KEY_PREFIX;


/**
 * @author 张 志 豪
 * @version 1.0
 */
@Service
public class EmailServiceImpl implements EmailService {
    @Value("${spring.mail.username}")
    private String from;   // 邮件发送人

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private JavaMailSender mailSender;//他们其实会自动去配置文件里面找到授权码等信息的

    public boolean sendMsg(String to) {
        //校验邮箱
        if (StrUtil.isBlank(to) || !EmailRightUtils.isRightEmail(to)){
            throw new BusinessException(ResultCodeEnum.EMAIL_NOT_EXIST);
        }

        SimpleMailMessage mailMessage = new SimpleMailMessage();
        //生成随机6位验证码
        String code = RandomUtil.randomNumbers(6);
        mailMessage.setFrom(from);
        mailMessage.setTo(to);
        String subject = "AI应用中心QQ邮箱验证码";
        String context = String.format("您的验证码是：%s，请在2分钟内完成验证。", code);
        mailMessage.setSubject(subject);//头部头字段 (xxx登录系统注册验证码)
        mailMessage.setText(context); //消息体 (xxx您的验证码是xxx)

        // 真正的发送邮件操作，从 from到 to
        try {
            mailSender.send(mailMessage);
        } catch (Exception e) {
            e.printStackTrace();//打印异常信息
            System.out.println("发送邮件出现异常: " + e.getMessage());
            return false;//表示发送失败(可能就是我们的邮箱不对！)
        }
        System.out.println("测试邮件发送成功 to: "  + to + " 验证码: " + code);
        stringRedisTemplate.opsForValue().set(EMAIL_CODE_KEY_PREFIX+ from,code,120, TimeUnit.MINUTES);//redis存储,2分钟过期
        return true;//表示发送成功
    }

    public static void main(String[] args) {
        // 生成6位数字验证码
        String code = RandomUtil.randomNumbers(6);
        System.out.println(code);
    }
}